package communication;

import storageclasses.Bank;
import storageclasses.MedicalRecord;

public class CommandParser {
	private byte[] response;;
	private int action;
	private String patient_nbr;
	private String comment;
	private String nurseForNew;
	private String id;
	private static final int ACTION = 0;
	private static final int PERS_NBR_START = 1;
	private static final int PERS_NBR_END = 10;
	private static final int COMMENT_START = 11;
	private LoginInfo li;

	public CommandParser(byte[] data, int length, LoginInfo li) {
		this.li = li;
		if (length < 11) {
			response = "ERROR: Not enough information provided!".getBytes();
			return;
		}
		action = Integer.parseInt("" + (char) data[ACTION]);
		patient_nbr = byteToString(data, PERS_NBR_START, PERS_NBR_END);
		if (action == 1 || action == 3) {
			comment = byteToString(data, COMMENT_START, length);
			if (action == 3) {
				nurseForNew = comment.substring(0, 10);
				comment = comment.substring(10);
			} else if (action == 1) {
				id = comment.split("===")[0];
				comment = comment.split("===")[1];
			}

		}
		System.out.println("Action: " + action);
		System.out.println("Patient: " + patient_nbr);
		System.out.println("Comment: " + comment);
	}

	public static String byteToString(byte[] a, int from, int to) {
		StringBuilder sb = new StringBuilder();
		for (int i = from; i <= to; i++) {
			sb.append((char) a[i]);
		}
		return sb.toString();
	}

	public byte[] getResponse(Bank bank, String[][] personellMatrix) {
		if (response != null) {
			return response;
		}

		int pos = getReqAccLevel(personellMatrix);
		int currentAccess = (pos >= 0) ? Integer
				.parseInt(personellMatrix[pos][2]) : 0;
		String division = (pos >= 0) ? personellMatrix[pos][3] : "Ingen division";
				
				
		if (action == 0) {
			return bank.getMedicalRecords(patient_nbr, li.LOGIN_PRSNBR, division
					,currentAccess).getBytes();

		}
		if (action == 1 && pos > -1) {
			return bank.writeToMedicalRecord(Integer.parseInt(id), patient_nbr,
					li.LOGIN_PRSNBR, personellMatrix[pos][3], currentAccess, comment).getBytes();
		}
		if (action == 2 && pos > -1) {
			return bank.removeAll(patient_nbr, li.LOGIN_PRSNBR, currentAccess).getBytes();
		}
		if (action == 3 && pos > -1) {
			MedicalRecord mr = new MedicalRecord(li.LOGIN_PRSNBR, nurseForNew,
					personellMatrix[pos][3], comment);
			return bank.addRecord(patient_nbr, li.LOGIN_PRSNBR, mr,currentAccess).getBytes();
		}

		return null;
	}

	private int getReqAccLevel(String[][] personellMatrix) {
		for (int k = 0; k < personellMatrix.length; k++) {
			if (personellMatrix[k][0].equals(li.LOGIN_PRSNBR)) {
				return k;
			}
		}
		return -1;
	}

}
